<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="108px">
      <el-form-item label="计划" prop="planId">
        <el-select v-model="queryParams.planId" @change="planChangeEvent" placeholder="请选择计划" size="small">
           <el-option
              v-for="item in planList"
              :key="item.planId"
              :label="item.planName"
              :value="item.planId"
            ></el-option>            
        </el-select>
      </el-form-item>
      <el-form-item label="系统" prop="sysLel">
        <el-cascader v-model="queryParams.sysLel"
                expand-trigger="hover"
                change-on-select
                :options="sysTemTreeList"
                :props="{label:'label',value:'id',children:'children' }"
                >
        </el-cascader>
      </el-form-item>

      <el-form-item label="任务名称" prop="nodeTask">
        <el-input
          v-model="queryParams.nodeTask"
          placeholder="请输入任务名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间">
        <el-date-picker
          v-model="daterangeStartDate"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间">
        <el-date-picker
          v-model="daterangeEndDate"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="责任部门" prop="deptId">
        <el-select v-model="queryParams.deptId" placeholder="请选择责任部门" clearable size="small">
           <el-option
              v-for="item in deptList"
              :key="item"
              :label="item"
              :value="item"              
            ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['project:project:add']"
        >新增</el-button>
      </el-col>     
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['project:project:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['project:project:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
      <el-table-column label="类别" align="center" prop="milestone" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_milestone" :value="scope.row.milestone"/>
        </template>
      </el-table-column>
      <el-table-column label="系统" align="left" prop="sysLel1Name" :show-overflow-tooltip="true"/>
      <el-table-column label="分系统" align="left" prop="sysLel2Name" :show-overflow-tooltip="true"/>
      <el-table-column label="子系统" align="left" prop="sysLel3Name" :show-overflow-tooltip="true"/>
      <el-table-column label="计划描述" align="left" prop="nodeTask" :show-overflow-tooltip="true"/>
      <el-table-column label="开始时间" align="left" prop="startDate" width="100" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="left" prop="endDate" width="100" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="责任部门" align="left" prop="deptId" :show-overflow-tooltip="true"/>
      <el-table-column label="交付物" align="left" prop="haveDone" :show-overflow-tooltip="true"/>
      <el-table-column label="前置任务" align="left" prop="dependName" :show-overflow-tooltip="true"/>
      <el-table-column label="执行状态" align="left" prop="status" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.project_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['project:project:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['project:project:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工程管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
             <el-form-item label="计划" prop="planId">
                <el-select v-model="form.planId" @change="planChangeEvent" placeholder="请选择计划" clearable size="small">
                  <el-option
                      v-for="item in planList"
                      :key="item.planId"
                      :label="item.planName"
                      :value="item.planId"
                    ></el-option>            
                </el-select>
              </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务名称" prop="nodeTask" >
              <el-input v-model="form.nodeTask" placeholder="请输入任务名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="系统" prop="sysLel" >
              <el-cascader
                expand-trigger="hover"
                change-on-select
                :options="sysTemTreeList"
                :props="{label:'label',value:'id',children:'children' }"
                v-model="form.sysLel">
              </el-cascader>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="依赖任务" prop="dependId">
              <el-select v-model="form.dependId" 
                        filterable
                        placeholder="请选择依赖任务">
                <el-option
                  v-for="item in taskList"
                  :key="item.taskId"
                  :label="item.nodeTask"
                  :value="item.taskId"              
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
              <el-form-item label="开始时间" prop="startDate">
                <el-date-picker clearable size="small"
                  v-model="form.startDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择开始时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间" prop="endDate">
                <el-date-picker clearable size="small"
                  v-model="form.endDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择结束时间">
                </el-date-picker>
              </el-form-item>    
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
             <el-form-item label="责任部门" prop="deptId">
              <el-select v-model="form.deptId" 
                        filterable
                        allow-create
                        placeholder="请选择责任部门">
                <el-option
                  v-for="item in deptList"
                  :key="item"
                  :label="item"
                  :value="item"              
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否里程碑" prop="milestone">
              <el-radio-group v-model="form.milestone">
                <el-radio
                  v-for="dict in dict.type.sys_normal_milestone"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>        
            </el-form-item>  
          </el-col>
        </el-row>

        <el-form-item label="完成输出物" prop="haveDone">
          <el-input v-model="form.haveDone" placeholder="请输入完成输出物" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>





     <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?planId=' + upload.planId"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">  
          <div class="el-upload__tip" slot="tip" style="margin:5px;">            
            <el-select v-model="upload.planId" clearable size="small" placeholder="请选择计划">
                <el-option
                    v-for="item in planList"
                    :key="item.planId"
                    :label="item.planName"
                    :value="item.planId"
                  ></el-option>            
            </el-select>
          </div>        
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listProject, getProject, delProject, addProject, 
         updateProject, exportProject, getDistinctSystem, 
         importTemplate, getDistinctDept, getDistinctTask } from "@/api/project/project";

import {getDictTree} from '@/api/system/dict/data'
import { planSelect } from "@/api/project/plan";         
import { getToken } from "@/utils/auth";

export default {
  name: "Project",
  dicts: ['sys_normal_milestone','project_status'],
  data() {
    return {
      planId: null,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工程管理表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 责任部门时间范围
      daterangeStartDate: [],
      // 责任部门时间范围
      daterangeEndDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskId: null,
        sysLel1: null,
        sysLel2: null,
        nodeTask: null,
        startDate: null,
        endDate: null,
        milestone: null,
        haveDone: null,
        dependId: null,
        deptId: null,
        planId: null,
      },
      // 表单参数
      form: {
        planId:''
      },
      // 表单校验
      rules: {
         planId: [
          { required: true, message: "计划不能为空", trigger: "blur" },
        ],
        nodeTask: [
          { required: true, message: "任务描述不能为空", trigger: "blur" },
          { min: 2, max: 200, message: '任务描述长度必须介于 2 和 200 之间', trigger: 'blur' }
        ],
        sysLel: [
          { required: true, message: "系统不能为空", trigger: "blur" }          
        ],       
        startDate: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endDate: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "责任部门不能为空", trigger: "blur" },
        ],
      },
      sysTemTreeList:[],
      deptList:[],
      taskList:[],
      planList:[],
      
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        planId: null,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/project/project/importData"
      },
    };
  },
  created() {
    this.planId = this.$route.params && this.$route.params.planId;
    this.planSelect() ;
    this.getDistinctDept();
    this.getSystemTree();

    if(parseInt(this.planId)) {
      this.queryParams.planId = parseInt(this.planId) ;
      this.form.planId        = parseInt(this.planId) ;   
      this.planChangeEvent(this.form.planId);     
      this.getList();
    } else {
      this.planId = null;
    }
    this.loading = false;
  },
  methods: {
    /** 查询工程管理列表 */
    getList() {
      this.loading = true;
      if(this.queryParams.planId == null) {
        this.$modal.msgWarning("请选择计划");
        this.loading = false;
        return ;
      }
      this.queryParams.params = {};
      if (null != this.daterangeStartDate && '' != this.daterangeStartDate) {
        this.queryParams.params["beginStartDate"] = this.daterangeStartDate[0];
        this.queryParams.params["endStartDate"] = this.daterangeStartDate[1];
      }
      if (null != this.daterangeEndDate && '' != this.daterangeEndDate) {
        this.queryParams.params["beginEndDate"] = this.daterangeEndDate[0];
        this.queryParams.params["endEndDate"] = this.daterangeEndDate[1];
      }
      listProject(this.queryParams).then(response => {
        this.projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        planId: parseInt(this.planId),
        taskId: null,
        sysLel1: null,
        sysLel2: null,
        nodeTask: null,
        startDate: null,
        endDate: null,
        milestone: '0',
        haveDone: null,
        dependId: null,
        deptId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeStartDate = [];
      this.daterangeEndDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.taskId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加任务节点";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const taskId = row.taskId || this.ids
      getProject(taskId).then(response => {
        this.form = response.data;
        this.form.sysLel = [] ;
        if(this.form.sysLel1 !=null) {
          this.form.sysLel.push(this.form.sysLel1);
        }
        if(this.form.sysLel2 !=null) {
          this.form.sysLel.push(this.form.sysLel2);
        }
        if(this.form.sysLel3 !=null) {
          this.form.sysLel.push(this.form.sysLel3);
        }
        this.open = true;
        this.title = "修改任务节点";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.taskId != null) {
            updateProject(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProject(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const taskIds = row.taskId || this.ids;
      this.$modal.confirm('是否确认删除工程管理编号为"' + taskIds + '"的数据项？').then(function() {
        return delProject(taskIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      if(this.queryParams.planId == null) {
        this.$modal.msgWarning("请选择计划");
        return ;
      }
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出计划编排明细数据？').then(() => {
        this.exportLoading = true;
        return exportProject(queryParams);
      }).then(response => {
        this.$download.name(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    },
    planChangeEvent(value) {
       getDistinctTask({planId: value}).then(response => {
        this.taskList = response.rows ;
      }) ;
    },
    getDistinctDept() {
      getDistinctDept().then(response => {
        this.deptList = response.rows ;
      })
    },  
    planSelect() {
      planSelect().then(response => {
        this.planList = response.rows ;
      })
    },
    getSystemTree() {
      getDictTree('plan_sys').then(response => {
        this.sysTemTreeList = response.data ;
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "计划编排导入";
      this.upload.open = true;
    },
     /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.$download.name(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      if(this.upload.planId == null) {
        this.$modal.msgWarning("请选择计划");        
      } else {
        this.$refs.upload.submit();
      }
    },
    tableRowClassName({row, rowIndex}){
      if(row.status == '4') {
          return 'warning-row';
      } else if(row.status != '3') {
        let a = this.getNowDate();
        if(row.endDate < a) {
          return 'warning-row';
        }
      }
    },
    getNowDate() {
        var  date =  new  Date();
        var  seperator1 =  "-" ;
        var  year = date.getFullYear();
        var  month = date.getMonth() + 1;
        var  strDate = date.getDate();
        if  (month >= 1 && month <= 9) {
          month =  "0"  + month;
        }
        if  (strDate >= 0 && strDate <= 9) {
          strDate =  "0"  + strDate;
        }
        var  currentdate = year + seperator1 + month + seperator1 + strDate;
        return  currentdate;
      }

  }
};
</script>

<style>
  .el-table .warning-row {
      color: #FF4400;
    }
</style>